package com.cmcc.groupcontacts.numbersearch.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cmcc.groupcontacts.base.BaseActivity;
import com.cmcc.groupcontacts.numbersearch.adapter.SearchNumberAdapter;
import com.cmcc.groupcontacts.numbersearch.dao.SearchNumberDao;
import com.cmcc.groupcontacts.numbersearch.model.SearchNumber;
import com.cmcc.groupcontacts.util.ValidationUtil;
import com.cmcc.groupcontacts.view.MyTitlePanel;
import com.yinhai.activity.R;

public class NumberSearchResultActivity extends BaseActivity {

	MyTitlePanel titlePanel;
	private static final int CTX_MENU_CALL = 0;
	private static final int CTX_MENU_EDIT_BEFORE_CALL = 1;
	private static final int CTX_MENU_SEND_CARD = 2;
	// private static final int CTX_MENU_VIEW_DETAIL = 3;
	private static final int CTX_MENU_SAVE_CONTACTER = 3;
	private int p = 0;// 点击次数,点一次分一页
	private int pageSize = 30; // 每页显示记录数
	private ProgressBar progressBar;
	private boolean isRefreshing;
	private LinearLayout loadingLayout;
	private TextView emptyText;
	private ListView listView;
	private ArrayList<SearchNumber> searchResult;
	private SearchNumberAdapter listItemAdapter;
	protected SearchNumber curItem;
	private String key;
	private int categoryId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.number_search_result_activity);

		Intent intent = getIntent();
		key = intent.getStringExtra("key");
		categoryId = intent.getIntExtra("categoryId", 0);

		listView = (ListView) findViewById(R.id.number_search_listview);
		emptyText = (TextView) findViewById(R.id.emptyText);
		initListView();
		search();

		titlePanel = (MyTitlePanel) findViewById(R.id.title_panel);
		titlePanel.setActivity(this);
	}

	private void search() {
		SearchNumberDao dao = new SearchNumberDao();
		if (categoryId != 0) {
			searchResult = dao.loadByCategory(categoryId);
		} else if (!ValidationUtil.isNullOrEmpty(key)) {
			searchResult = dao.loadByKey(key);
		}

		listItemAdapter = new SearchNumberAdapter(getBaseContext(),
				searchResult);
		listView.setAdapter(listItemAdapter);
	}

	private void initListView() {
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				if (!ValidationUtil.isNullOrEmpty(searchResult)
						&& position < searchResult.size()) {
					call(searchResult.get(position).number);
				}
			}
		});

		// listView.setOnScrollListener(new AbsListView.OnScrollListener() {
		//
		// private boolean shouldRefresh;
		//
		// @Override
		// public void onScrollStateChanged(AbsListView view, int scrollState) {
		// if (shouldRefresh && scrollState ==
		// OnScrollListener.SCROLL_STATE_IDLE) {
		// if (isRefreshing == false) {
		// isRefreshing = true;
		// p++;
		// // cacheMap.clear();
		//
		// // mSearch.goToPoiPage(p);
		// // search();
		// // startNetSearch();
		// }
		// }
		// }
		//
		// @Override
		// public void onScroll(AbsListView view, int firstVisibleItem, int
		// visibleItemCount, int totalItemCount) {
		// shouldRefresh = false;
		//
		// boolean isNotEmpty = (totalItemCount > 0);
		// boolean isNotLessThanPageSize = (totalItemCount >= pageSize);
		// boolean isLoadMore = (view.getLastVisiblePosition() >= totalItemCount
		// - 1);
		// if (isNotEmpty && isNotLessThanPageSize && isLoadMore) {
		// shouldRefresh = true;
		// }
		// }
		// });

		listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				curItem = (SearchNumber) listView.getItemAtPosition(position);
				return false;
			}

		});

		listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {

			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle(curItem.name);
				if (!ValidationUtil.isNullOrEmpty(curItem.number)) {
					String numbers = curItem.number.replace(" ", "");
					if (numbers.indexOf(",") > 0) {
						String[] nums = numbers.split(",");
						for (String num : nums) {
							menu.add(0, CTX_MENU_CALL, 0,
									getString(R.string.common_call) + num);
						}
					} else {
						menu.add(0, CTX_MENU_CALL, 0,
								getString(R.string.common_call)
										+ curItem.number.replace(" ", ""));
					}
					menu.add(0, CTX_MENU_EDIT_BEFORE_CALL, 2,
							R.string.common_edit_before_call);
				}
				menu.add(0, CTX_MENU_SAVE_CONTACTER, 3,
						R.string.common_save_contacter);
				menu.add(0, CTX_MENU_SEND_CARD, 4, R.string.common_send_card);
			}

		});

		// listView.addFooterView(createLoadingLayout(), null, false);
		// listView.setAdapter(listItemAdapter);

		emptyText = (TextView) findViewById(R.id.emptyText);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CTX_MENU_CALL:// 呼叫
			String title = item.getTitle().toString();
			String[] ary = title.split(" ");
			call(ary[ary.length - 1]);
			break;
		case CTX_MENU_EDIT_BEFORE_CALL:// 呼叫前编辑
			String numbers = curItem.number.replace(" ", "");
			if (numbers.indexOf(",") > 0) {
				final String[] nums = numbers.split(",");
				AlertDialog.Builder b = new AlertDialog.Builder(this);
				b.setItems(nums, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String num = nums[which];
						final EditText text = new EditText(
								NumberSearchResultActivity.this);
						text.setText(num);
						new AlertDialog.Builder(NumberSearchResultActivity.this)
								.setView(text)
								.setTitle(R.string.common_edit_before_call)
								.setPositiveButton(R.string.ok,
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												String number = text.getText()
														.toString().trim()
														.replace("-", "");
												if (!ValidationUtil
														.isNullOrEmpty(number)) {
													call(number);
												}
											}
										})
								.setNegativeButton(R.string.cancel, null)
								.show();
					}
				});
				b.show();
			} else {
				final EditText text = new EditText(this);
				text.setText(curItem.number.replace(" ", ""));
				new AlertDialog.Builder(this)
						.setView(text)
						.setTitle(R.string.common_edit_before_call)
						.setPositiveButton(R.string.ok,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										String number = text.getText()
												.toString().trim()
												.replace("-", "");
										if (!ValidationUtil
												.isNullOrEmpty(number)) {
											call(number);
										}
									}
								}).setNegativeButton(R.string.cancel, null)
						.show();
			}
			break;
		case CTX_MENU_SEND_CARD:// 发送电子名片
			sms("", curItem.name + ":" + curItem.number.replace("-", ""));
			break;
		case CTX_MENU_SAVE_CONTACTER:// 添加联系人
			Intent intent = new Intent(Intent.ACTION_INSERT);
			intent.setType("vnd.android.cursor.dir/person");
			intent.setType("vnd.android.cursor.dir/contact");
			intent.setType("vnd.android.cursor.dir/raw_contact");
			intent.putExtra("phone", curItem.number.replace("-", ""));
			intent.putExtra("name", curItem.name);
			startActivity(intent);
			break;
		default:
			break;
		}

		return false;
	}

	private LinearLayout createLoadingLayout() {
		LinearLayout.LayoutParams WClayoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		LinearLayout.LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT);
		LinearLayout layout = new LinearLayout(this);
		// 设置布局 水平方向
		layout.setOrientation(LinearLayout.HORIZONTAL);
		// 进度条
		progressBar = new ProgressBar(this);
		// 进度条显示位置
		progressBar.setPadding(0, 0, 15, 0);

		layout.addView(progressBar, WClayoutParams);

		TextView textView = new TextView(this);
		textView.setText("加载中...");
		textView.setGravity(Gravity.CENTER_VERTICAL);

		layout.addView(textView, FFlayoutParams);
		layout.setGravity(Gravity.CENTER);

		loadingLayout = new LinearLayout(this);
		loadingLayout.addView(layout, WClayoutParams);
		loadingLayout.setGravity(Gravity.CENTER);
		loadingLayout.setOrientation(LinearLayout.HORIZONTAL);
		return loadingLayout;
	}

	private void call(String number) {
		try {
			number = number.replace("-", "");
			Intent intent = new Intent(Intent.ACTION_DIAL);
			intent.setData(Uri.fromParts("tel", number, null));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), "呼叫失败！", Toast.LENGTH_SHORT)
					.show();
		}
	}

	private void sms(String number, String content) {
		try {
			Uri smsToUri = Uri.parse("smsto:" + number);
			Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("sms_body", content);
			startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), "发送短信失败！", Toast.LENGTH_SHORT)
					.show();
		}
	}
}
